package com.centaline.androidsalesblog.activities.sale;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.entrust.ReservationListActivity;
import com.centaline.androidsalesblog.activities.map.AroundMapActivity;
import com.centaline.androidsalesblog.activities.mine.BindingPhoneActivity;
import com.centaline.androidsalesblog.activities.mine.LoanCalcActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.activities.mine.TaxCalcActivity;
import com.centaline.androidsalesblog.activities.newest.NearbyNewEstListActivity;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.api.newest.NewEstListApi;
import com.centaline.androidsalesblog.api.sale.AgentCommentApi;
import com.centaline.androidsalesblog.api.sale.PostDetailApi;
import com.centaline.androidsalesblog.api.sale.PostInternalApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.AppNameType;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SourceType;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.events.ReserveUpdate;
import com.centaline.androidsalesblog.iml.ImgViewPagerClickListener;
import com.centaline.androidsalesblog.iml.StaffItemDetailOnClick;
import com.centaline.androidsalesblog.model.businissobject.AgentCommentBo;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.businissobject.PostDetailBo;
import com.centaline.androidsalesblog.model.businissobject.PostImgBo;
import com.centaline.androidsalesblog.model.businissobject.PostInternalBo;
import com.centaline.androidsalesblog.model.businissobject.ShareBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.AgentCommentRo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.NewEstListRo;
import com.centaline.androidsalesblog.model.responseobject.PostDetailRo;
import com.centaline.androidsalesblog.model.responseobject.PostInternalRo;
import com.centaline.androidsalesblog.model.responseobject.ReservationRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.utils.BdMapUtil;
import com.centaline.androidsalesblog.utils.CentaDistanceUtil;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.PriceUtil;
import com.centaline.androidsalesblog.utils.ResponseCheck;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centaline.androidsalesblog.widgets.ConsultView;
import com.centaline.androidsalesblog.widgets.DetailImgLayout;
import com.centaline.androidsalesblog.widgets.DetailToolsView;
import com.centaline.androidsalesblog.widgets.ShareDialog;
import com.centaline.androidsalesblog.widgets.chart.SaleLineChart;
import com.centaline.androidsalesblog.widgets.chart.SalePieChart;
import com.centaline.androidsalesblog.widgets.dropdown.SpecialLoadView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.SprfUtil;
import com.centanet.framework.widget.AbstractSpecialLoadView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 二手房详情
 */
public class SaleDetailActivity extends BaseActivity implements View.OnClickListener {

    private SpecialLoadView specialLoadView;
    private AppCompatTextView atv_price, atv_cal, atv_house_type, atv_area, atv_price_unit,
            atv_floor, atv_orientations, atv_fitment, atv_build_year, atv_feature,
            atv_esf_estate, atv_guide, atv_address, atv_map_name, atv_nav,
            atv_num_price, atv_num_nearby;
    private RelativeLayout rl_deal_history, rl_new_est, rl_guide, rl_guide_content, rl_map, rl_esf_of_nearby;
    private ImageView img_arrow_address, img_map;
    private DetailImgLayout detailImgLayout;
    private ViewStub vs_sale_metro, vs_sale_school, vs_tools, vs_line, vs_pie;
    private View overView;
    private ConsultView consultView;
    private BottomSheetBehavior bottomSheetBehavior;
    private DetailToolsView detailToolsView;

    private DrawableRequestBuilder<String> requestBuilder;
    private ArrayList<PostImgBo> postImgBoArrayList = new ArrayList<>();
    private ArrayList<String> imgList = new ArrayList<>();//小图列表
    private ArrayList<String> imgListH = new ArrayList<>();//大图列表
    private String postId;
    private PostDetailBo postDetailBo;

    private boolean newPropEnable;//新房是否可用
    private boolean collect;//是否收藏
    private String collectId;
    private LocationClient locationClient;

    private String descriptionSplitChar;
    private String shareUrl;
    private ShareDialog shareDialog;
    private String userPhone;
    private int refreshTag = 0;//0.不刷新 1.加约看 2.查看约看单

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_sale_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        specialLoadView = (SpecialLoadView) findViewById(R.id.specialLoadView);
        atv_price = (AppCompatTextView) findViewById(R.id.atv_price);
        atv_cal = (AppCompatTextView) findViewById(R.id.atv_cal);
        atv_house_type = (AppCompatTextView) findViewById(R.id.atv_house_type);
        atv_area = (AppCompatTextView) findViewById(R.id.atv_area);
        atv_price_unit = (AppCompatTextView) findViewById(R.id.atv_price_unit);
        atv_floor = (AppCompatTextView) findViewById(R.id.atv_floor);
        atv_orientations = (AppCompatTextView) findViewById(R.id.atv_orientations);
        atv_fitment = (AppCompatTextView) findViewById(R.id.atv_fitment);
        atv_build_year = (AppCompatTextView) findViewById(R.id.atv_build_year);
        atv_feature = (AppCompatTextView) findViewById(R.id.atv_feature);
        atv_esf_estate = (AppCompatTextView) findViewById(R.id.atv_esf_estate);
        atv_guide = (AppCompatTextView) findViewById(R.id.atv_guide);
        atv_address = (AppCompatTextView) findViewById(R.id.atv_address);
        img_arrow_address = (ImageView) findViewById(R.id.img_arrow_address);
        atv_map_name = (AppCompatTextView) findViewById(R.id.atv_map_name);
        atv_nav = (AppCompatTextView) findViewById(R.id.atv_nav);
        img_map = (ImageView) findViewById(R.id.img_map);
        detailImgLayout = (DetailImgLayout) findViewById(R.id.detailImgLayout);
        vs_sale_metro = (ViewStub) findViewById(R.id.vs_sale_metro);
        vs_sale_school = (ViewStub) findViewById(R.id.vs_sale_school);
        vs_line = (ViewStub) findViewById(R.id.vs_line);
        vs_pie = (ViewStub) findViewById(R.id.vs_pie);
        atv_num_price = (AppCompatTextView) findViewById(R.id.atv_num_price);
        atv_num_nearby = (AppCompatTextView) findViewById(R.id.atv_num_nearby);
        rl_deal_history = (RelativeLayout) findViewById(R.id.rl_deal_history);
        rl_new_est = (RelativeLayout) findViewById(R.id.rl_new_est);
        rl_guide = (RelativeLayout) findViewById(R.id.rl_guide);
        rl_guide_content = (RelativeLayout) findViewById(R.id.rl_guide_content);
        rl_map = (RelativeLayout) findViewById(R.id.rl_map);
        rl_esf_of_nearby = (RelativeLayout) findViewById(R.id.rl_esf_of_nearby);
        vs_tools = (ViewStub) findViewById(R.id.vs_tools);
        overView = findViewById(R.id.overView);
        consultView = (ConsultView) findViewById(R.id.consultView);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initViews() {
        requestBuilder = GlideLoad.init(this);
        detailImgLayout.setRequestBuilder(requestBuilder);
        detailImgLayout.setImgViewPagerClickListener(new ImgViewPagerClickListener() {
            @Override
            public void imgItemClick(int position) {
                startActivity(new Intent(SaleDetailActivity.this, PostImgListBrowseActivity.class)
                        .putExtra(ExtraConstant.IMG_LIST, imgListH)
                        .putExtra(ExtraConstant.IMG_LIST_THUMBNAIL, imgList)
                        .putExtra(ExtraConstant.IMG_POS, position)
                        .putExtra(PostImgListBrowseActivity.POST_IMG_LIST, postImgBoArrayList));
            }
        });
        specialLoadView.setLoadStatusListener(new AbstractSpecialLoadView.LoadStatusListener() {
            @Override
            public void load() {
                mainRequest();
            }
        });
        atv_cal.setOnClickListener(this);
        consultView.initRequestBuilder(GlideLoad.initRound(this), new StaffItemDetailOnClick() {
            @Override
            public void onClick(final StaffDo staffDo, int tag, String imContent, String msgContent) {
                switch (tag) {
                    case 0:
                        startActivity(new Intent(SaleDetailActivity.this, StaffDetailActivity.class)
                                .putExtra(ExtraConstant.StaffNo, staffDo.getStaffNo()));
                        break;
                    case 1:
                        startActivity(new Intent(SaleDetailActivity.this, ChatActivity.class)
                                .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffDo.getStaffNo()))
                                .putExtra(ExtraConstant.MessageTarget, 1)
                                .putExtra(ExtraConstant.MessageTargetValue, postId)
                                .putExtra(ExtraConstant.MessageCome, imContent));
                        baiduEvent("C5_4_Click");
                        break;
                    case 2:
                        ContactUtil.sendMsg(SaleDetailActivity.this, staffDo.getMobile(), msgContent);
                        baiduEvent("C5_5_Click");
                        break;
                    case 3:
                        new AlertDialog.Builder(SaleDetailActivity.this)
                                .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                        staffDo.getBigCode(), staffDo.getExtCode()))
                                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ContactUtil.dial(SaleDetailActivity.this, staffDo.getBigCode(), staffDo.getExtCode());
                                        baiduEvent("C5_3_Click");
                                    }
                                }).setNegativeButton("取消", null)
                                .create()
                                .show();
                        break;
                    default:
                        break;
                }
                if (tag != 0) {
                    RxDataBase.saveStaff(staffDo)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .compose(SaleDetailActivity.this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Action1<Void>() {
                                @Override
                                public void call(Void aVoid) {

                                }
                            });
                }
            }
        });
        bottomSheetBehavior = BottomSheetBehavior.from(consultView);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                overView.setAlpha(slideOffset);
                overView.setVisibility(slideOffset > 0 ? View.VISIBLE : View.GONE);
            }
        });

        postId = getIntent().getStringExtra(ExtraConstant.PostId);

        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                NaviParaOption naviParaOption = new NaviParaOption();
                                naviParaOption.startPoint(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()))
                                        .endPoint(new LatLng(postDetailBo.getLat(),
                                                postDetailBo.getLng()));
                                BaiduMapNavigation.openBaiduMapNavi(naviParaOption, SaleDetailActivity.this);
                                break;
                            default:
                                snack("定位失败");
                                break;
                        }
                    }
                });
        atv_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });
        userInfo();
        bizUnit();
        mainRequest();
    }

    /**
     * 主体数据请求
     */
    private void mainRequest() {
        PostDetailApi postDetailApi = new PostDetailApi(RentDetailActivity.class, PostDetailRo.class,
                new IResponseListener<PostDetailRo>() {
                    @Override
                    public void onResponse(PostDetailRo postDetailRo) {
                        if (ResponseCheck.check(postDetailRo)) {
                            specialLoadView.loadSuccess();
                            postDetailBo = postDetailRo.getPostDetailBo();
                            setData();
                        } else {
                            specialLoadView.loadError();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        specialLoadView.loadError();
                    }
                });
        postDetailApi.setPostId(postId);
        postDetailApi.startRequest();
    }

    private void setData() {
        setToolbarTitle(postDetailBo.getPostDo().getCnEstate());
        atv_price.setText(PriceUtil.salePrice(postDetailBo.getSellPrice()));
        atv_house_type.setText(String.format(Locale.CHINA, "%d室%d厅", postDetailBo.getRoomCnt(), postDetailBo.getHallCnt()));
        atv_area.setText(String.format(Locale.CHINA, "%.0f平", postDetailBo.getGArea()));
        atv_price_unit.setText(String.format(Locale.CHINA, "%.0f元/平", postDetailBo.getUnitSellPrice()));
        atv_floor.setText(postDetailBo.getFloor() == 0 ?
                String.format(Locale.CHINA, "%s/%d层", postDetailBo.getFloorDisplay(),
                        postDetailBo.getFloorTotal()) :
                String.format(Locale.CHINA, "%d/%d层", postDetailBo.getFloor(), postDetailBo.getFloorTotal()));
        atv_orientations.setText(postDetailBo.getDirection());
        atv_fitment.setText(postDetailBo.getFitment());
        String opDate = DateUtil.format(postDetailBo.getOpDate(), DateUtil.FORMAT1, DateUtil.FORMAT3);
        if (TextUtils.isEmpty(opDate) ||
                "1900".equals(opDate)) {
            atv_build_year.setText("暂无资料");
        } else {
            atv_build_year.setText(String.format(Locale.CHINA, "%s年", opDate));
        }
        ArrayList<String> features = postDetailBo.getPostDo().getKeyWords();
        atv_feature.setText(features == null || features.size() == 0 ?
                "暂无资料" :
                String.format(Locale.CHINA, "%s", postDetailBo.getPostDo().getKeyWords().toString().replace("[", "").replace("]", "").replace(",", "、")));
        atv_esf_estate.setText(postDetailBo.getCestName());
        atv_address.setText(String.format("%s-%s  %s", postDetailBo.getReginName(),
                postDetailBo.getBlockName(), postDetailBo.getDisplayAddress()));
        detailImgLayout.setTitle(postDetailBo.getTitle());
        detailImgLayout.setTencentVistaUrl(postDetailBo.getTencentVistaUrl());
        if (!TextUtils.isEmpty(postDetailBo.getRailWayName())) {
            if (vs_sale_metro != null) {
                vs_sale_metro.inflate();
                AppCompatTextView atv_metro_info = (AppCompatTextView) findViewById(R.id.atv_metro_info);
                if (atv_metro_info != null) {
                    atv_metro_info.setText(String.format(Locale.CHINA, "%s", CentaDistanceUtil.distanceOfPostAndMetro(postDetailBo.getRailLineNames(),
                            postDetailBo.getRailWayName(), postDetailBo.getRailWayDistance())));
                }
            }
        }
        if (vs_sale_school != null &&
                !TextUtils.isEmpty(postDetailBo.getSchoolToEstate())) {
            vs_sale_school.inflate();
            AppCompatTextView atv_school_info = (AppCompatTextView) findViewById(R.id.atv_school_info);
            if (atv_school_info != null) {
                atv_school_info.setText(postDetailBo.getSchoolToEstate());
            }
        }

        /*房贷参考*/
        if (postDetailBo.getSellPrice() > 0 &&
                vs_pie != null) {
            vs_pie.inflate();
            SalePieChart salePieChart = (SalePieChart) findViewById(R.id.salePieChart);
            AppCompatTextView atv_tax = (AppCompatTextView) findViewById(R.id.atv_tax);
            if (salePieChart != null) {
                salePieChart.setTotalPriceAndRate(postDetailBo.getSellPrice(), 0.049);
                salePieChart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putDouble(ExtraConstant.LOAN_PRICE, postDetailBo.getSellPrice());
                        startActivity(new Intent(SaleDetailActivity.this, LoanCalcActivity.class)
                                .putExtra(ExtraConstant.LOAN_BUNDLE, bundle));
                    }
                });
            }
            /*税费参考*/
            if (atv_tax != null) {
                double tax;
                if (postDetailBo.getGArea() > 90) {
                    tax = postDetailBo.getSellPrice() * 1.5 / 100 + 5;
                    atv_tax.setText(String.format(Locale.CHINA, "%.0f 元", tax));
                } else {
                    tax = postDetailBo.getSellPrice() / 100 + 5;
                    atv_tax.setText(String.format(Locale.CHINA, "%.0f 元", tax));
                }
            }
        }
        rl_esf_of_nearby.setVisibility(View.VISIBLE);
        atv_num_price.setText(String.format(Locale.CHINA, "%s套", postDetailBo.getPricePosts()));
        atv_num_nearby.setText(String.format(Locale.CHINA, "%s套", postDetailBo.getRoundPosts()));
        if (vs_tools != null) {
            vs_tools.inflate();
            detailToolsView = (DetailToolsView) findViewById(R.id.detailToolsView);
            if (detailToolsView != null) {
                detailToolsView.setStaffs(postDetailBo.getStaffDos());
                detailToolsView.setYueKanOnClick(new DetailToolsView.YueKanOnClick() {
                    @Override
                    public void gotoYueKanBill() {
                        gotoReservationBill();
                    }

                    @Override
                    public void addYueKan() {
                        addReservation();
                    }

                    @Override
                    public void consult() {
                        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    }
                });
            }
            consultView.setPostDetail(postDetailBo);
            consultView.setStaffs(postDetailBo.getStaffDos());
        }

        atv_map_name.setText(postDetailBo.getPostDo().getCnEstate());
        if (postDetailBo.getLat() != 0 &&
                postDetailBo.getLng() != 0) {
            img_arrow_address.setVisibility(View.VISIBLE);
            atv_nav.setVisibility(View.VISIBLE);
            rl_map.setVisibility(View.VISIBLE);
            GlideLoad.load(new GlideLoad.Builder(requestBuilder,
                    BdMapUtil.getBaiduMapImgUrl(postDetailBo.getLng(), postDetailBo.getLat()))
                    .placeHolder(R.drawable.ic_banner)
                    .error(R.drawable.ic_banner)
                    .openWifiSwitch()
                    .into(img_map));
        }

        invalidateOptionsMenu();

        otherRequest();

        reserveCount();

        RxDataBase.fpHistorySave(1, postId, postDetailBo.getPostDo())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
    }

    /**
     * 其他数据请求
     */
    private void otherRequest() {
        /*图片*/
        RxRequest.postImg(SaleDetailActivity.class, postId)
                .compose(this.<ArrayList<PostImgBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<PostImgBo>>() {
                    @Override
                    public void call(ArrayList<PostImgBo> postImgBos) {
                        if (postImgBos != null) {
                            postImgBoArrayList.clear();
                            postImgBoArrayList.addAll(postImgBos);
                            imgList.clear();
                            imgListH.clear();
                            for (PostImgBo postImgBo : postImgBoArrayList) {
                                imgList.add(postImgBo.getPath());
                                imgListH.add(postImgBo.getHdPath());
                            }
                            detailImgLayout.setImgList(imgList);
                        }
                    }
                });

        AgentCommentApi agentCommentApi = new AgentCommentApi(SaleDetailActivity.class, AgentCommentRo.class,
                new IResponseListener<AgentCommentRo>() {
                    @Override
                    public void onResponse(AgentCommentRo agentCommentRo) {
                        if (agentCommentRo != null) {
                            ArrayList<AgentCommentBo> temp = agentCommentRo.getList();
                            if (temp != null &&
                                    temp.size() > 0) {
                                rl_guide.setVisibility(View.VISIBLE);
                                rl_guide_content.setVisibility(View.VISIBLE);
                                if (TextUtils.isEmpty(descriptionSplitChar) ||
                                        !temp.get(0).getPostDirection().contains(descriptionSplitChar)) {
                                    atv_guide.setText(temp.get(0).getPostDirection());
                                } else {
                                    atv_guide.setText(temp.get(0).getPostDirection().replaceAll(descriptionSplitChar, "\n"));
                                }
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        agentCommentApi.setPostId(postId);
        agentCommentApi.setPageCount(1);
        agentCommentApi.startRequest();

        //折线图请求API
        PostInternalApi postInternalApi = new PostInternalApi(EsfEstateDetailActivity.class, PostInternalRo.class,
                new IResponseListener<PostInternalRo>() {
                    @Override
                    public void onResponse(PostInternalRo postInternalRo) {
                        if (postInternalRo != null) {
                            ArrayList<PostInternalBo> postInternalBos = postInternalRo.getList();
                            if (postInternalBos != null &&
                                    postInternalBos.size() > 0) {
                                boolean show = false;
                                for (PostInternalBo postInternalBo : postInternalBos) {
                                    if (postInternalBo != null &&
                                            "estate".equalsIgnoreCase(postInternalBo.getType()) &&
                                            postInternalBo.getDealListBos() != null &&
                                            postInternalBo.getDealListBos().size() > 2) {
                                        show = true;
                                    }
                                }
                                if (show && vs_line != null) {
                                    rl_deal_history.setVisibility(View.VISIBLE);
                                    vs_line.inflate();
                                    SaleLineChart saleLineChart = (SaleLineChart) findViewById(R.id.saleLineChart);
                                    if (saleLineChart != null) {
                                        saleLineChart.setPostInternalBos(postDetailBo.getCestName(), postInternalBos);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        postInternalApi.setCestcode(postDetailBo.getCestCode());
        postInternalApi.setGscopeid(String.valueOf(postDetailBo.getGscopeId()));
        postInternalApi.startRequest();

        //周边小区同价位
//        if (postDetailBo != null &&
//                postDetailBo.getLat() != 0 &&
//                postDetailBo.getLng() != 0) {
//            PostListApi postListApi = new PostListApi(SaleDetailActivity.class, PostListRo.class,
//                    new IResponseListener<PostListRo>() {
//                        @Override
//                        public void onResponse(PostListRo postListRo) {
//                            atv_num_nearby.setText(String.format(Locale.CHINA, "%s套", postListRo.getTotal()));
//                        }
//
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//
//                        }
//                    });
//            postListApi.setLatLng(new LatLng(postDetailBo.getLat(), postDetailBo.getLng()));
//            postListApi.setRound("1000");
//            double samePrice = postDetailBo.getSellPrice();
//            postListApi.setMin(String.format(Locale.CHINA, "%.0f", samePrice * 0.9));
//            postListApi.setMax(String.format(Locale.CHINA, "%.0f", samePrice * 1.1));
//            postListApi.startRequest();
//        }

        /*周边新盘*/
        if (newPropEnable &&
                postDetailBo.getLat() != 0 &&
                postDetailBo.getLng() != 0) {
            NewEstListApi newEstListApi = new NewEstListApi(SaleDetailActivity.class, NewEstListRo.class,
                    new IResponseListener<NewEstListRo>() {
                        @Override
                        public void onResponse(NewEstListRo newEstListRo) {
                            if (newEstListRo.getTotal() > 0)
                                rl_new_est.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
            double avgPrice = postDetailBo.getUnitSellPrice();
            if (avgPrice > 0) {
                newEstListApi.setMinAveragePrice(String.format(Locale.CHINA, "%.0f", avgPrice * 0.9));
                newEstListApi.setMaxAveragePrice(String.format(Locale.CHINA, "%.0f", avgPrice * 1.1));
                newEstListApi.setLatLng(new LatLng(postDetailBo.getLat(), postDetailBo.getLng()));
                newEstListApi.setSortBy("2");
                newEstListApi.startRequest();
            }
        }

        collectStatus();
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        showLoadingDialog();
        locationClient.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_pie_chart:
            case R.id.atv_cal://房贷计算
                Bundle bundle = new Bundle();
                bundle.putDouble(ExtraConstant.LOAN_PRICE, postDetailBo.getSellPrice());
                startActivity(new Intent(this, LoanCalcActivity.class)
                        .putExtra(ExtraConstant.LOAN_BUNDLE, bundle));
                baiduEvent("C5_1_Click");
                break;
            case R.id.rl_est_estate://小区
                if (postDetailBo != null)
                    startActivity(new Intent(this, EsfEstateDetailActivity.class)
                            .putExtra(ExtraConstant.CestCode, postDetailBo.getCestCode()));
                break;
            case R.id.rl_guide://购房指引
            case R.id.rl_guide_content:
                startActivity(new Intent(this, AgentCommentActivity.class)
                        .putExtra(ExtraConstant.PostId, postId));
                break;
            case R.id.rl_address://地图
            case R.id.img_map:
                if (postDetailBo == null ||
                        postDetailBo.getLat() == 0 || postDetailBo.getLng() == 0) {
                    snack("地理位置获取失败");
                } else {
                    startActivity(new Intent(this, AroundMapActivity.class)
                            .putExtra(ExtraConstant.LatLng, new LatLng(postDetailBo.getLat(), postDetailBo.getLng()))
                            .putExtra(ExtraConstant.MAP_NAME, postDetailBo.getCestName()));
                }
                break;
            case R.id.rl_deal_history://成交历史
                startActivity(new Intent(this, EsfDealHistoryActivity.class)
                        .putExtra(ExtraConstant.CestCode, postDetailBo.getCestCode()));
                break;
            case R.id.rl_esf_of_price:
                if (postDetailBo != null) {
                    startActivity(new Intent(this, EsfSaleOfPriceActivity.class)
                            .putExtra(ExtraConstant.CestCode, postDetailBo.getCestCode())
                            .putExtra(ExtraConstant.Price, postDetailBo.getSellPrice()));
                }
                break;
            case R.id.rl_esf_of_nearby:
                if (postDetailBo != null) {
                    startActivity(new Intent(this, EsfSaleOfNearbyActivity.class)
                            .putExtra(ExtraConstant.Price, postDetailBo.getSellPrice())
                            .putExtra(ExtraConstant.LatLng, new LatLng(postDetailBo.getLat(), postDetailBo.getLng())));

                }
                break;
            case R.id.rl_new_est:
                startActivity(new Intent(this, NearbyNewEstListActivity.class)
                        .putExtra(ExtraConstant.Price, postDetailBo.getUnitSellPrice()));
                break;
            case R.id.overView:
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                break;
            case R.id.rl_pie_tax: //税费计算
                Bundle bund = new Bundle();
                bund.putDouble(ExtraConstant.TAX_DAN_PRICE, postDetailBo.getUnitSellPrice());
                bund.putDouble(ExtraConstant.Area, postDetailBo.getGArea());
                bund.putDouble(ExtraConstant.TAX_TOTAL_PRICE, postDetailBo.getSellPrice());
                startActivity(new Intent(this, TaxCalcActivity.class)
                        .putExtra(ExtraConstant.TAX_BUNDLE, bund));
                break;
            default:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        reserveCount();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_collect_share, menu);
        MenuItem shareItem = menu.findItem(R.id.action_share);
        shareItem.setVisible(postDetailBo != null && !TextUtils.isEmpty(shareUrl));
        MenuItem collectItem = menu.findItem(R.id.action_collect);
        collectItem.setVisible(postDetailBo != null);
        collectItem.setIcon(collect ? R.drawable.ic_collected : R.drawable.ic_uncollected);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (R.id.action_collect == item.getItemId()) {
            collect();
        } else if (R.id.action_share == item.getItemId()) {
            if (shareDialog == null) {
                ShareBo shareBo = new ShareBo(0);
                shareBo.setHouseName(postDetailBo.getCestName());
                shareBo.setHouseDecription(postDetailBo.getTitle());
                shareBo.setHouseType(String.format(Locale.CHINA, "%d室%d厅",
                        postDetailBo.getRoomCnt(), postDetailBo.getHallCnt()));
                shareBo.setArea(String.format(Locale.CHINA, "%.0f平", postDetailBo.getGArea()));
                shareBo.setTotalPrice(String.format(Locale.CHINA, "%.0f万", postDetailBo.getSellPrice() / 10000));
                shareBo.setHouseUrl(shareUrl.replace("{0}", postId));
                shareBo.setImageUrl(postDetailBo.getPostDo().getThumbPath());
                shareDialog = new ShareDialog(this, shareBo);
                baiduEvent("C5_2_Type");
            }
            shareDialog.show();
        }
        return super.onOptionsItemSelected(item);
    }

    private void collect() {
        if (AppConstant.IsLogin) {
            if (collect) {
                RxRequest.cancelCollect(SaleDetailActivity.class, collectId)
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collect = false;
                                    EventBus.getDefault().post(new MineInfoUpdate(11));
                                    invalidateOptionsMenu();
                                    snack(R.string.collect_cancel);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            } else {
                RxRequest.addCollect(SaleDetailActivity.class, AppNameType.ESF, SourceType.ERSHOUFANG, collectId, postId,
                        String.format(Locale.CHINA, "%s%s?postId=%s", AppConstant.SaleUrl, "Post", postId))
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collect = true;
                                    if (0 != simpleUserCenterRo.getResult()) {
                                        collectId = String.valueOf(simpleUserCenterRo.getResult());
                                    }
                                    EventBus.getDefault().post(new MineInfoUpdate(11));
                                    invalidateOptionsMenu();
                                    SprfUtil.setInt(SaleDetailActivity.this,
                                            String.format("%s_%s", SprfConstant.COLLECT_POSITION, AppConstant.CityCode), 11);
                                    snack(R.string.collect_success);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                    collectStatus();
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_COLLECT);
        }
    }

    /**
     * 收藏状态
     */
    private void collectStatus() {
        if (AppConstant.IsLogin) {
            RxRequest.collectStatus(SaleDetailActivity.class, postId,
                    String.format(Locale.CHINA, "%s%s?postId=%s", AppConstant.SaleUrl, "Post", postId))
                    .compose(this.<CollectInfoListRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CollectInfoListRo>() {
                        @Override
                        public void call(CollectInfoListRo collectInfoListRo) {
                            final ArrayList<CollectInfoBo> temp = collectInfoListRo.getList();
                            if (temp != null &&
                                    temp.size() > 0) {
                                collectId = String.valueOf(temp.get(0).getCollectID());
                                collect = !temp.get(0).isDel();
                            } else {
                                collect = false;
                            }
                            invalidateOptionsMenu();
                        }
                    });
        }
    }

    /**
     * 获取配置
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        descriptionSplitChar = bizUnitDo.getDescriptionSplitChar();
                        consultView.setImEnable(bizUnitDo.isShowTalk());
                        newPropEnable = bizUnitDo.isEnableNewprop();
                        shareUrl = bizUnitDo.getShareEsf();
                        invalidateOptionsMenu();
                    }
                });
    }

    /**
     * 用户信息
     */
    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo != null)
                            userPhone = userDo.getPhone();
                        if (refreshTag == 1) {
                            addReservation();
                        } else if (refreshTag == 2) {
                            gotoReservationBill();
                        }
                    }
                });
    }

    /**
     * 添加约看
     */
    private void addReservation() {
        refreshTag = 1;
        if (AppConstant.IsLogin) {
            if (TextUtils.isEmpty(userPhone)) {
                startActivityForResult(new Intent(this, BindingPhoneActivity.class),
                        CommonConstant.REQ_BIND_MOBILE);
            } else {
                showLoadingDialog();
                RxRequest.addReservation(getClass(), "s", postDetailBo.getCestCode(), postDetailBo.getCestName(), postId)
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                cancelLoadingDialog();
                                switch (simpleUserCenterRo.getResultNo()) {
                                    case 0:
                                        EventBus.getDefault().post(new ReserveUpdate(0));
                                        reserveCount();
                                        snack("已加入约看");
                                        break;
                                    case -2:
                                        snack("该房源已在您的约看单中");
                                        break;
                                    case -3:
                                        snack("约看单只能添加十套房源");
                                        break;
                                    default:
                                        snack(simpleUserCenterRo.getMessage());
                                        break;
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class),
                    CommonConstant.REQ_BIND_MOBILE);
        }
    }

    /**
     * 查看约看单
     */
    private void gotoReservationBill() {
        refreshTag = 2;
        if (AppConstant.IsLogin) {
            if (TextUtils.isEmpty(userPhone)) {
                startActivityForResult(new Intent(SaleDetailActivity.this, BindingPhoneActivity.class),
                        CommonConstant.REQ_BIND_MOBILE);
            } else {
                startActivity(new Intent(SaleDetailActivity.this, ReservationListActivity.class)
                        .putExtra(ExtraConstant.EXTRA_POSITION, 0));
            }
        } else {
            startActivityForResult(new Intent(SaleDetailActivity.this, LoginActivity.class),
                    CommonConstant.REQ_BIND_MOBILE);
        }
    }

    /**
     * 约看数量
     */
    private void reserveCount() {
        if (AppConstant.IsLogin) {
            RxRequest.reserveCount(getClass())
                    .compose(this.<ReservationRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<ReservationRo>() {
                        @Override
                        public void call(ReservationRo reservationRo) {
                            if (detailToolsView != null) {
                                detailToolsView.setReserveCount(reservationRo.getTotal());
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            if (detailToolsView != null) {
                                detailToolsView.setReserveCount(0);
                            }
                        }
                    });
        }
    }

    @Subscribe
    public void onEventMainThread(ReserveUpdate reserveUpdate) {
        reserveCount();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConstant.REQ_COLLECT:
                    collect();
                    break;
                case CommonConstant.REQ_BIND_MOBILE:
                    userInfo();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
